package com.simple.cloud.core.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.simple.cloud.core.consts.CommonCst.RESP_CONTENT_TYPE;

/**
 * 响应工具类
 */
@Slf4j
public class RespUtil {
    /**
     *
     */
    public static void writeResp(HttpServletResponse response, Object obj) {
        writeResp(response, 200, obj);
    }

    /**
     *
     */
    public static void writeResp(HttpServletResponse response, int status, Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.findAndRegisterModules();
        response.setContentType(RESP_CONTENT_TYPE);
        response.setStatus(status);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(objectMapper.writeValueAsString(obj));
            response.flushBuffer();
        } catch (Exception e) {
            log.error("[{}]执行方法报错", RespUtil.class.getName(), e);
        }
    }

}
